﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ASoft.Data;
using System.IO;
using ASoft.Service;
using NLog;
using ASoft.Msg;
using ASoft.Base;

namespace ASoft
{
    /// <summary>
    /// RC
    /// </summary>
    public class RC
    {
        static RC _rc;
        static RC()
        {
            _rc = new RC();
        }

        public static RC Current
        {
            get
            {
                return _rc;
            }
        }

        SerialPortService _SerialPortService;
        public SerialPortService SerialPortService
        {
            get
            {
                if (_SerialPortService == null)
                {
                    _SerialPortService = new SerialPortService();
                }
                return _SerialPortService;
            }
        }

        #region RootData

        RootData _RootData;
        public RootData RootData
        {
            get
            {
                if (_RootData == null)
                {
                    ReLoadRootData();
                }
                return _RootData;
            }
        }

        Dictionary<byte, MsgBase> roomLastMsgs = new Dictionary<byte, MsgBase>();
        public Dictionary<byte, MsgBase> RoomLastMsgs { get { return roomLastMsgs; } }

        public void SaveRootData()
        {
            AppUtility.SerializerWrite<RootData>(RootData, GetRootFileName(), null);
        }

        public void ReLoadRootData()
        {
            _RootData = LoadRootData();
            SerialPortService.PortName = RootData.PLCData.PortName;
        }

        public RootData LoadRootData()
        {
            var fileName = GetRootFileName();
            if (File.Exists(fileName))
            {
                FileInfo fi = new FileInfo(fileName);
                if (fi.Length > 0)
                {
                    return AppUtility.SerializerRead<RootData>(fileName, null);
                }
            }
            var result = new RootData();
            AppUtility.SerializerWrite<RootData>(result, fileName, null);
            return result;
        }

        string GetRootFileName()
        {
            return Path.Combine(ConfigInfo.RootPath, AppUtility.GetFileName("root"));
        }


        #endregion

        #region PositonData

        PositionData _PositionData;
        public PositionData PositionData
        {
            get
            {
                if (_PositionData == null)
                {
                    _PositionData = LoadPositionData();
                }
                return _PositionData;
            }
        }

        public void SavePositionData()
        {
            AppUtility.SerializerWrite<PositionData>(PositionData, GetPositionDataFileName(), null);
        }

        public PositionData LoadPositionData()
        {
            var fileName = GetPositionDataFileName();
            if (File.Exists(fileName))
            {
                FileInfo fi = new FileInfo(fileName);
                if (fi.Length > 0)
                {
                    return AppUtility.SerializerRead<PositionData>(fileName, null);
                }
            }
            var result = new PositionData();
            AppUtility.SerializerWrite<PositionData>(result, fileName, null);
            return result;
        }

        string GetPositionDataFileName()
        {
            return Path.Combine(ConfigInfo.RootPath, AppUtility.GetFileName("position"));
        }

        #endregion

        Logger _Loger;
        public Logger Loger
        {
            get
            {
                if (_Loger == null)
                {
                    _Loger = LogManager.GetCurrentClassLogger();
                }
                return _Loger;
            }
        }

        Logger _ErrorLoger;
        public Logger ErrorLoger
        {
            get
            {
                if (_ErrorLoger == null)
                {
                    _ErrorLoger = LogManager.GetLogger("error");
                }
                return _ErrorLoger;
            }
        }

        MsgService _MsgService;
        public MsgService MsgService
        {
            get
            {
                if (_MsgService == null)
                {
                    _MsgService = new MsgService(this.SerialPortService);
                }
                return _MsgService;
            }
        }

        PhoneMsgService _PhoneMsgService;
        public PhoneMsgService PhoneMsgService
        {
            get
            {
                if (_PhoneMsgService == null)
                {
                    _PhoneMsgService = new PhoneMsgService();
                    _PhoneMsgService.MsgOK += PhoneMsgService_MsgOK;
                }
                return _PhoneMsgService;
            }
        }

        void PhoneMsgService_MsgOK(object sender, PhoneMsgEventArgs e)
        {
            try
            {
                PhoneMsgs.Add(e.Msg);
            }
            catch { }
        }
        List<PhoneMsg> _PhoneMsgs;
        public List<PhoneMsg> PhoneMsgs
        {
            get
            {
                if (_PhoneMsgs == null)
                {
                    _PhoneMsgs = new List<PhoneMsg>();
                }
                return _PhoneMsgs;
            }
        }

        TcpService _TcpService;
        public TcpService TcpService
        {
            get
            {
                if (_TcpService == null)
                {
                    _TcpService = new TcpService();
                }
                return _TcpService;
            }
        }

        public void SetRoomCount(byte count)
        {
            if (RootData.温室集合.Count == count)
            {
                return;
            }
            if (count < 0)
            {
                RootData.温室集合.Clear();
                SaveRootData();
                return;
            }
            if (RootData.温室集合.Count > count)
            {
                RootData.温室集合.RemoveAll(p => p.Id > count);
            }
            else
            {
                for (int i = RootData.温室集合.Count + 1; i <= count; i++)
                {
                    RootData.温室集合.Add(new Msg.RoomData()
                    {
                        Id = (byte)i,
                        RoomName = i.ToString() + "#",
                        RoomGroupName = "无"
                    });
                }
            }
            SaveRootData();
        }

        public WeatherStationReturnMsgBase 气象站实时数据 { get; set; }

        public EWeatherStationDataStyle 气象站实时数据来源方式 { get; set; }

        #region Login
        #endregion

        public bool IsLogin { get; private set; }

        public string LoginUserCode { get; private set; }

        public string LoginUserName { get; private set; }

        public bool IsAdmin { get; private set; }

        public bool IsSysAdmin { get; set; }

        public void LoginIn(string code, string password)
        {
            if (string.Equals(code, "admin", StringComparison.CurrentCultureIgnoreCase))
            {
                if (string.Equals(password, "nimda", StringComparison.CurrentCultureIgnoreCase))
                {
                    this.IsAdmin = true;
                    this.IsSysAdmin = true;
                    this.IsLogin = true;
                    this.LoginUserCode = "Admin";
                    this.LoginUserName = "系统管理员";
                    return;
                }
                throw new Exception("用户名或密码错误.");
            }

            var user = Current.RootData.Users.FirstOrDefault(p =>
                string.Equals(code, p.Code, StringComparison.CurrentCultureIgnoreCase));
            if (user == null)
            {
                throw new Exception("用户名或密码错误.");
            }

            if (!user.ValidatePassword(password))
            {
                throw new Exception("用户名或密码错误.");
            }

            this.IsLogin = true;
            this.IsAdmin = user.IsAdmin;
            this.IsSysAdmin = false;
            this.LoginUserCode = user.Code;
            this.LoginUserName = user.Name;
        }

        /// <summary>
        /// 是否正在监控
        /// </summary>
        public bool IsMonitoring { get; set; }
    }
}
